//
//  ImmersiveView.swift
//  testc
//
//  Created by Ares Cheuk on 2024/3/30.
//

import SwiftUI
import RealityKit
import RealityKitContent

struct ImmersiveView: View {
    @State var axZoomIn: Bool = false
    @State var axZoomOut: Bool = false
    
    let notificationName = "CcNotification"
    let notificationDeleteName = "CcNotificationDeleteAll"

    
    @State var productEmtity : [String] = []

    var body: some View {
        
        VStack{
            
            ForEach(0..<productEmtity.count, id:\.self) { index in
                RealityView { content in
                    // Add the initial RealityKit content
                    if let scene = try? await Entity(named: productEmtity[index], in: realityKitContentBundle) {
                        content.add(scene)
                    }
       
                }.placementGestures(
                    initialPosition: Point3D([475, -1200.0, -1300.0]),
                    axZoomIn: axZoomIn,
                    axZoomOut: axZoomOut)
            }
        
        }.onAppear{
            
            ///收到通知
            NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue:notificationName), object: nil, queue: .main) { Notification in
                
                //动态加载到数组里面 
                productEmtity.append(Notification.object as! String)
            }
            
            ///收到删除通知
            NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue:notificationDeleteName), object: nil, queue: .main) { Notification in
                
                //删除动态加载的数据
                productEmtity.removeAll()
            }
            
        }.onDisappear(){
            NotificationCenter.default.removeObserver(NSNotification.Name(rawValue:notificationName))
        }
    }
}

#Preview(immersionStyle: .mixed) {
    ImmersiveView()
}
